package main

import (
	"context"
	"gateway/global/model"
	comment "gateway/kitex_gen/comment"
)

// CommentServiceImpl implements the last service interface defined in the IDL.
type CommentServiceImpl struct{}

// Comment implements the CommentServiceImpl interface.
func (s *CommentServiceImpl) Comment(ctx context.Context, req *comment.CommentReq) (resp *comment.CommentResp, err error) {
	// TODO: Your code here...
	return
}

// UserList implements the CommentServiceImpl interface.
func (s *CommentServiceImpl) UserList(ctx context.Context, req *comment.UserListReq) (resp *comment.UserListResp, err error) {
	// TODO: Your code here...
	var users []model.User
	db := model.DB.Model(&model.User{})
	if req.Status != 0 {
		switch req.Status {
		case 1:
			db = db.Where("status = ?", "正常")
			break
		case 2:
			db = db.Where("status = ?", "封禁")
			break
		}
	}
	if req.Phone != "" {
		db = db.Where("phone like ?", "%"+req.Phone+"%")
	}
	var total int64
	db.Count(&total)
	db.Find(&users)
	res := []*comment.User{}
	for _, user := range users {
		var r = comment.User{
			NickName:  user.NickName,
			CreatedAt: user.CreatedAt.String(),
			Phone:     user.Phone,
			Status:    user.Status,
		}
		res = append(res, &r)
	}
	return &comment.UserListResp{
		Users:      res,
		TotalData:  total,
		TotalLevel: total/15 + 1,
	}, nil
}

// DriverList implements the CommentServiceImpl interface.
func (s *CommentServiceImpl) DriverList(ctx context.Context, req *comment.DriverListReq) (resp *comment.DriverListResp, err error) {
	// TODO: Your code here...
	var drives []struct {
		model.Drive
		CarCode   string
		CarBrand  string
		CarStatus string
	}
	db := model.DB.Model(&model.Drive{})
	db = db.Joins("join cars on cars.id = drives.car_id")
	if req.Status != 0 {
		db = db.Where("drives.status = ?", req.Status)
	}
	if req.Form != "" {
		db = db.Where("drives.form_name like ?", "%"+req.Form+"%")
	}
	if req.Order != 0 {
		db = db.Order("drives.created_at desc")
	}
	var total int64
	db.Select("drives.*,cars.car_code as car_code,cars.car_brand as car_brand,car_status as car_status").Count(&total).Find(&drives)
	res := []*comment.Driver{}
	for _, drive := range drives {
		var r = comment.Driver{
			DriveId:   int64(drive.ID),
			Phone:     drive.Phone,
			CarCode:   drive.CarCode,
			CarBrand:  drive.CarBrand,
			CarStatus: drive.CarStatus,
		}
		res = append(res, &r)
	}
	data := comment.DriverListResp{
		Driver:     res,
		TotalData:  total,
		TotalLevel: total/15 + 1,
	}
	return &data, nil
}
